package com.copd.controller;

import com.copd.common.Result;
import com.copd.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class JwtController {

    @Autowired
    private JwtService jwtService;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 验证用户名和密码
        if (jwtService.validateUser(username, password)) {
            // 生成token
            String token = jwtService.generateToken(username);
            
            // 构建返回数据
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("username", username);
            
            return Result.success("登录成功", response);
        } else {
            return Result.error("400", "用户名或密码错误");
        }
    }

    @PostMapping("/verify")
    public Result<Map<String, Object>> verifyToken(@RequestHeader("Authorization") String token) {
        if (jwtService.validateToken(token)) {
            String username = jwtService.getUsernameFromToken(token);
            Map<String, Object> response = new HashMap<>();
            response.put("username", username);
            return Result.success("token验证成功", response);
        } else {
            return Result.error("400", "token无效或已过期");
        }
    }
} 